/*
 * @Author: liaoxin
 * @Date: 2022-03-08 17:34:24
 * @LastEditors: Setsuna
 * @LastEditTime: 2023-07-20 16:30:51
 * @FilePath: \src\pages\UserManagement\DealerAccount\list.tsx
 */
import React from 'react'
import { Button, Modal, message, Select, Form, Row, Col, Input } from 'antd'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, uaaApp, UdModal, http } from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { resetPassword, enableHandle } from '../common'
import apis from '@/apis/UserManagement'
import _ from 'lodash'
import dayjs from 'dayjs'
import UpdateDealerAccountModal from '../component/UpdateDealerAccountModal'
import comApis from '@/apis'
import { deepLoopFormateTree } from '@/utils/methods'

const confirm = Modal.confirm
const Option = Select.Option

const EnableBtnAuth = 'user_dealer_account_manager_invalid'
const ResetPasswordBtnAuth = 'user_dealer_account_manager_rest_password'
const UntieBtnAuth = 'user_dealer_account_manager_untie'
const ManagerUpdate = 'user_dealer_account_manager_update'

// 新增时所选区域的id
let modalChooseAreaId = ''

class DealerAccountList extends BaseListPage<IDealerAccountListProps, IDealerAccountListState> {

  protected saveParamsWithUrl: boolean = true

  private typeTranslate = {
    0: '经销商',
    1: '分销商',
  }

  private statusTranslate = {
    0: '禁用',
    1: '启用',
  }

  private typeOptions = [...Object.keys(this.typeTranslate).map(key => ({ value: key, name: this.typeTranslate[key] }))]
  private statusOptions = [...Object.keys(this.statusTranslate).map(key => ({ value: key, name: this.statusTranslate[key] }))]

  constructor(props: IDealerAccountListProps) {
    super(props)

    this.state = {
      title: '经销商账号管理',
      queryApi: apis.DealerAccountList,
      conditions: [
        { id: 'agentName', label: '客户名称' },
        { id: 'phone', label: '手机号码' },
        { id: 'userName', label: '联系人' },
        // { id: 'roleName', label: '角色' },
        {
          id: 'agentType', label: '用户类型', render:
            <Select placeholder='请输入用户类型'>
              {this.typeOptions.map(({ value, name }) => <Option key={value} value={value}>{name}</Option>)}
            </Select>
        },
        {
          id: 'isValid', label: '状态', render:
            <Select placeholder='请输入状态'>
              {this.statusOptions.map(({ value, name }) => <Option key={value} value={value}>{name}</Option>)}
            </Select>
        },
        { id: 'agentCode', label: '客户编码' }
      ],
      rowKey: 'id',
      columns: [
        ['客户编码', 'agentCode', null, { fixedWidth: '60px' }],
        ['客户名称', 'agentName', null, { minWidth: '180px' }],
        ['经营税号', 'socialCode', null, { minWidth: '80px' }],
        ['联系人', 'userName', null, { minWidth: '60px' }],
        ['手机号码', 'phone', null, { fixedWidth: '74px' }],
        ['用户类型', 'agentType', columnRenders.enum(this.typeTranslate), { fixedWidth: '60px' }],
        // ['角色', 'roleName', null, { minWidth: '80px', maxWidth: '300px', className: 'normal-nowrap' }],
        ['状态', 'isValid', columnRenders.enum(this.statusTranslate), { fixedWidth: '30px' }],
        ['创建时间', 'createdTime', (text) => <span>{dayjs(text).format('YYYY-MM-DD HH:mm:ss')}</span>, { fixedWidth: '110px' }],
        ['创建人', 'createdBy', null, { fixedWidth: '60px' }],
        ['最近修改时间', 'updatedTime', (text) => <span>{text && dayjs(text).format('YYYY-MM-DD HH:mm:ss')}</span>, { fixedWidth: '110px' }],
        ['最近修改人', 'updatedBy', null, { fixedWidth: '60px' }],
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '160px',
          fixed: 'right',
          render: columnRenders.operate([
            // {
            //   title: '编辑',auth: ManagerUpdate, action: (text, record) => this.openModalHandle(record)
            // },
            {
              title: '重置密码', auth: ResetPasswordBtnAuth, action: (text: any, record: any) => {
                // 设置默认的重置密码
                record.password = `Jxsmh@${parseInt(record.agentCode)}`;
                confirm({
                  title: '确定要重置登录密码吗？',
                  content:
                    <Form labelCol={{ span: 6 }} wrapperCol={{ span: 12 }}>
                      <Row gutter={24}>
                        <Col>
                          <Form.Item label={"设置密码"} required={true}>
                            <Input onChange={(e) => {
                              record.password = e.target.value;
                            }} defaultValue={`${record.password}`} />
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form>
                  ,
                  onOk: () => {
                    if (!record.password) {
                      message.error('请填写修改的密码');
                      return Promise.reject('请填写修改的密码');
                    }
                    const reg: any = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
                    if (!reg.test(record.password)) {
                      message.error('密码至少包含大写字母，小写字母，数字，且不少于8位');
                      return Promise.reject('密码至少包含大写字母，小写字母，数字，且不少于8位');
                    }
                    this.resetPassword(record);
                  }
                })
              }
            },
            {
              title: 'unionID解绑', auth: UntieBtnAuth, action: (text: any, record: any) => {
                confirm({
                  title: '确定要解绑unionID吗？',
                  onOk: () => {
                    return this.untie(record.id)
                  }
                })
              }
            },
          ])
        }
      ],
      leftBtns: [
        // <Button type='primary' onClick={() => this.openModalHandle()}>新增</Button>,
        uaaApp.canUse(EnableBtnAuth) && (() => <Button type="primary" disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(true)}>启用</Button>),
        uaaApp.canUse(EnableBtnAuth) && (() => <Button disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(false)}>禁用</Button>),
      ],
      tableProps: {
        scroll: { x: true },
        rowSelection: !uaaApp.canUse(EnableBtnAuth) ? null : {},
      },
      orgAreaList: [],
    }
  }

  untie = (userId: any) => {
    http.post(apis.untieUserUnionID, { userId }).then(() => {
      message.success('解绑成功')
      this.query()
    })
  }

  public openModalHandle = (row?) => {
    let initValues = {
      accountType: '1', // 默认经销商
      roleId: ['1'], // 默认主账号
      isValid: 1, // 默认启用
    }
    let title = '新增'
    if (row) {
      // 更新区域id为当前数据的组织id
      modalChooseAreaId = row.organization
      const agentName = { key: row.agentCode, lable: row.agentName }
      // 列表的businessPerson为业务员id，转换为接口所需字段userId
      const { roleId, businessPerson: userId, ...reset } = row
      initValues = { ...initValues, ...reset, agentName }
      title = '编辑经销商主账号'
    }
    const rowId = row?.id
    UdModal.open({
      title,
      content: <UpdateDealerAccountModal rowId={rowId} data={row} values={initValues} areaList={this.state.orgAreaList} areaSelectChangeHandle={this.updateAreaSelectChange} />,
      onOk: (values) => {
        const { agentName } = values
        delete values.roleId // 去掉roleId
        const params = {
          ...values,
          // labelInValue配置，默认值 lable ，select触发change后，得到的是 label
          agentName: agentName.label || agentName.lable,
          agentCode: agentName.key,
          // organization: modalChooseAreaId,
        }
        let url = apis.AddDealerAccount
        if (row && row.id) {
          params.id = row.id
          // params.agentId = row.agentId
          url = apis.UpdateDealerAccount
        }
        return http.put(url, params).then(res => {
          http.get(apis.pushUpdateDealerZdByDealerCode, { params: { dealerCode: values?.agentCode } }).then(resp => {
          })
          const msg = row ? '编辑成功' : '新增成功'
          message.success(msg)
          this.query()
        })
      }
    })
  }

  public updateAreaSelectChange = (id) => {
    modalChooseAreaId = id
  }

  private resetPassword = (row) => {
    const { id, password } = row;
    return resetPassword({
      url: apis.ResetDealerAccountPassword,
      params: { id: Number(id), password },
    })
  }

  private enableHandle = (flag) => {
    // 获取选择数据的id（账户id）操作启禁用，一户多开的账户，会存在重复
    const idList = this.state.selectedRows?.map(row => row.id)?.join(',')
    const isValid = flag ? 1 : 0
    enableHandle({
      flag,
      url: apis.EnableDealerAccount,
      params: {
        idList,
        isValid,
      },
      cb: () => {
        this.query()
      }
    })
  }

  // 获取当前用户组织树
  private getOrgTreeList = () => {
    http.get(comApis.OrganizationTreeByUser).then(res => {
      const datas = [res.data]
      const nodes = deepLoopFormateTree({ datas, translate: { value: 'value', title: 'title', key: 'key', children: 'children', extra: 'id' }, originKey: { value: 'code', title: 'name', children: 'children' } })
      this.setState({
        orgAreaList: nodes,
      })
    })
  }

  private frormatTreeData = (datas) => {
    if (!_.isArray(datas) || datas.length == 0) {
      return []
    }
    let nodes = []
    datas.map(item => {
      const { children, name: title, id, code: value, code: key } = item
      let treeNode = { id, key, value, title, children }
      treeNode.children = this.frormatTreeData(children)
      nodes.push(treeNode)
    })
    return nodes
  }

}

interface IDealerAccountListProps extends IBaseListPageProps {

}

interface IDealerAccountListState extends IBaseListPageState {
  orgAreaList: any[]
}

export default DealerAccountList
